package com.flower8.utils;

import com.flower8.sysconfig.constants.SysConstants;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Description: AES解密
 * @Author: tanglin
 * @Date: 2019/09/16 10:22
 * @Version: 1.0
 */
public class AES {
    public static void main(String[] args) {
        String content="国产的发顺丰22ss";

        System.out.println("加密后的密文为："+AESEncode(SysConstants.EMAIL_PRIVATE_KEY,content));
        System.out.println("解密后的明文为："+AESDecode(SysConstants.EMAIL_PRIVATE_KEY,AESEncode(SysConstants.EMAIL_PRIVATE_KEY,content)));
    }

    private static final String IV_STRING = "3A*by9e-740Uqpk&";

    /**
     * 加密
     * @param key
     * @param content
     * @return
     */
    public static String AESEncode( String key,String content) {
        try {
            byte[] byteContent = content.getBytes("UTF-8");
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            // 指定加密的算法、工作模式和填充方式
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] encryptedBytes = cipher.doFinal(byteContent);
            // 同样对加密后数据进行 base64 编码
            String AES_encode=new String(new BASE64Encoder().encode(encryptedBytes));
            //11.将字符串返回
            return AES_encode;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param key
     * @param content
     * @return
     */
    public static String AESDecode(String key,String content) {
        try {
            byte [] encryptedBytes= new BASE64Decoder().decodeBuffer(content);
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            byte[] result = cipher.doFinal(encryptedBytes);
            return new String(result, "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
